#!/usr/bin/env node
class Queue {
  constructor() {
    this.items = [];
  }

  write(data, consumer) {
    this.items.push(data);
    console.log('+ prd create:', data);
    // 检查是否有消费者准备消费数据
    if (this.items.length === 1) {
      consumer.destroy();
    }
  }

  read() {
    if (this.items.length === 0) {
      return null;
    }
    const data = this.items.shift();
    console.log('- csm destroy:', data);
    return data;
  }
}

class Producer {
  constructor(queue) {
    this.queue = queue;
  }

  create(data) {
    // 模拟生产数据的耗时操作
    setTimeout(() => {
      this.queue.write(data, consumer);
    }, 0);
  }
}

class Consumer {
  constructor(queue) {
    this.queue = queue;
  }

  destroy() {
    // 模拟消费数据的耗时操作
    setTimeout(() => {
      const data = this.queue.read();
      if (data !== null) {
        console.log('- csm destroy:', data);
      }
    }, 0);
  }
}

// 单例队列
const queue = new Queue();

// 实例化消费者
const consumer = new Consumer(queue);

function main() {
  const prd = new Producer(queue);
  for (let i = 0; i < 5; i++) {
    prd.create(i);
  }
}

main();